package com.immediatus.engine.input;

import android.view.MotionEvent;

public class MultiTouchController extends BaseTouchController{

    public MultiTouchController(){
    }

    @Override
    public boolean onHandleMotionEvent(final MotionEvent _event) {
        final int action = _event.getAction() & MotionEvent.ACTION_MASK;
        switch(action) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_POINTER_DOWN:
                return this.onHandleTouchAction(MotionEvent.ACTION_DOWN, _event);
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_POINTER_UP:
                return this.onHandleTouchAction(MotionEvent.ACTION_UP, _event);
            case MotionEvent.ACTION_CANCEL:
            case MotionEvent.ACTION_OUTSIDE:
                return this.onHandleTouchAction(action, _event);
            case MotionEvent.ACTION_MOVE:
                return this.onHandleTouchMove(_event);
        }
        return false;
    }

    private boolean onHandleTouchMove(final MotionEvent event_) {
        boolean handled = false;
        for(int i = event_.getPointerCount() - 1; i >= 0; i--) {
            final int pointerID = event_.getPointerId(i);
            final boolean handledInner = this.fireTouchEvent(event_.getX(i), event_.getY(i), MotionEvent.ACTION_MOVE, pointerID, event_);
            handled = handled || handledInner;
        }
        return handled;
    }

    private boolean onHandleTouchAction(final int action_, final MotionEvent event_) {
        final int pointerIndex = this.getPointerIndex(event_);
        final int pointerID = event_.getPointerId(pointerIndex);
        return this.fireTouchEvent(event_.getX(pointerIndex), event_.getY(pointerIndex), action_, pointerID, event_);
    }

    private int getPointerIndex(final MotionEvent event_) {
        return (event_.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
    }
}
